package com.ys.utils.spring.interceptor;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.ys.base.BaseConstants;
import com.ys.utils.base.j2se.DateHandler;
import com.ys.utils.base.j2se.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author quxinjun
 * @version 1.0.0
 * @ClassName DevCheckInterceptor.java
 * @Description 测试方法监控
 * @createTime 2021年06月07日 11:24:00
 */
@Slf4j
public class DevCheckInterceptor extends HandlerInterceptorAdapter {

    public DevCheckInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求开始时间
        request.setAttribute("_startTime", System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        // 请求结束时间
        Long endTime = System.currentTimeMillis();
        // 从HttpServletRequest获取开始时间
        Long startTime = (Long) request.getAttribute("_startTime");
        // 打印接口信息及耗时
        double v = (endTime - startTime) / 1000.0;
        if (!Logger.isTest() && !Logger.isOnline()) {
            Logger.info("{} {};耗时:{}s", ServletUtil.getClientIP(request, ""), getFullUrl(request), v);
            this.saveToLocalFile(request, v);
        }
    }

    private void saveToLocalFile(HttpServletRequest request, double v) {
        String fileUrl = "D:\\localFile\\";
        String name = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = fileUrl + name + ".txt";
        List<String> strList = new ArrayList<>();
        strList.add(DateHandler.getDate(new Date(), BaseConstants.BASE_FORMAT));
        String title = request.getMethod() + "\t" + ServletUtil.getClientIP(request) + "\t" + request.getRequestURL().toString() + "\t" + "耗时：" + v;
        strList.add(title);
        request.getParameterMap().forEach((key, value) -> {
            String paramStr = "[" + key + ":" + String.join(",", value) + "]";
            strList.add(paramStr);
        });
        strList.add("\n");
        FileUtil.appendLines(strList, fileName, "utf-8");
    }


    /**
     * 获取完整的URL路径
     *
     * @param request 请求对象
     * @return 完整的URL路径
     */
    private String getFullUrl(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        String method = request.getMethod();
        sb.append(method).append(" ");
        sb.append(request.getRequestURL().toString());
        return sb.toString();
    }

}
